package org.ss.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpClient {

    private static final Logger log = LoggerFactory.getLogger(HttpClient.class);

    private static final RequestConfig requestConfig;

    private static final RequestConfig uploadConfig;

    static {
        requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000*30)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(1000*30*3)
                .build();

        uploadConfig = RequestConfig.custom()
                .setConnectTimeout(1000*30*20)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(1000*30*20)
                .build();
    }

    public static String get(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.error("http 响应状态码：" + response.getStatusLine().getStatusCode());
                throw new RuntimeException("请求失败 状态码：" + response.getStatusLine().getStatusCode());
            }

        } catch (IOException | URISyntaxException e) {
            log.error("http 发送请求异常 url:{}", url, e);
            throw new RuntimeException("发送请求失败 url:" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("http 关闭流异常", e);
            }
        }
        return resultString;
    }

    public static String postFormData(String url, Map<String, String> formData){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            if (formData != null) {
                for (String key : formData.keySet()) {
                    multipartEntityBuilder.addTextBody(key, formData.get(key), ContentType.MULTIPART_FORM_DATA);
                }
            }

            httpPost.setEntity(multipartEntityBuilder.build());
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                throw new RuntimeException("请求失败 状态码：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("http 发送请求异常", e);
            throw new RuntimeException("发送请求失败 url:" + url);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error("http 关闭流异常", e);
            }
        }
        return resultString;
    }

    public static String post(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Charset.forName("UTF-8"));
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.error("http 响应状态码：" + response.getStatusLine().getStatusCode());
                throw new RuntimeException("请求失败 状态码：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("http 发送请求异常 url:{}", url, e);
            throw new RuntimeException("发送请求失败 url:" + url);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error("http 关闭流异常", e);
            }
        }
        return resultString;
    }

    public static String postJson(String url, String json) {
        if (!StringUtils.hasText(json)) {
            return null;
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("rwt", "read");

            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            httpPost.addHeader("rwt","read");

            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.error("http 响应状态码：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("http 发送请求异常 url:{}", url, e);
            throw new RuntimeException("发送请求失败 url:" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("Http 关闭流异常", e);
            }
        }
        return resultString;
    }

    public static Map<String,String> convertMap(JSONObject jsonObject) throws Exception{
        Map<String, Object> innerMap = jsonObject.getInnerMap();
        Map<String,String> map = convertMap(innerMap);
        return map;
    }

    private static Map<String, String> convertMap(Map<String,Object> objectMap) throws Exception{
        Map<String,String> map = new HashMap<>();
        for(Map.Entry<String,Object> entries : objectMap.entrySet()){
            map.put(entries.getKey(), null==entries.getValue() ? null :String.valueOf(entries.getKey()));
        }
        return map;
    }
}
